package com.xiaoshuidi.cloud.module.rooms.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoshuidi.cloud.framework.common.exception.ErrorCode;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.framework.common.util.json.JsonUtils;
import com.xiaoshuidi.cloud.module.rooms.api.apartment.ApartmentApi;
import com.xiaoshuidi.cloud.module.bpm.api.reserveapartmentconfig.ReserveApartmentConfigApi;
import com.xiaoshuidi.cloud.module.bpm.api.reserveapartmentconfig.vo.CreateReserveApartmentConfigReqVO;
import com.xiaoshuidi.cloud.module.rooms.api.apartment.dto.ApartmentListDto;
import com.xiaoshuidi.cloud.module.rooms.api.apartment.vo.RecommendApartmentInfoRespVO;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.apartment.vo.*;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomel.vo.RoomelUpdateReqVO;
import com.xiaoshuidi.cloud.module.rooms.controller.app.apartment.vo.ApartmentGuessListResp;
import com.xiaoshuidi.cloud.module.rooms.convert.apartment.ApartmentConvert;
import com.xiaoshuidi.cloud.module.rooms.enums.ReservationConfigStatusEnum;
import com.xiaoshuidi.cloud.module.rooms.framework.utils.BaiDuMapUtil;
import com.xiaoshuidi.cloud.module.rooms.framework.utils.CodeUtil;
import com.xiaoshuidi.cloud.module.rooms.mapper.ApartmentMapper;
import com.xiaoshuidi.cloud.module.rooms.mq.producer.RoomEsProducer;
import com.xiaoshuidi.cloud.module.rooms.pojo.Apartment;
import com.xiaoshuidi.cloud.module.rooms.pojo.RoomHouse;
import com.xiaoshuidi.cloud.module.rooms.pojo.RoomLayout;
import com.xiaoshuidi.cloud.module.rooms.pojo.RoomReservationConfig;
import com.xiaoshuidi.cloud.module.rooms.repository.*;
import com.xiaoshuidi.cloud.module.rooms.service.ApartmentService;
import com.xiaoshuidi.cloud.module.rooms.service.BaiDuMapService;
import com.xiaoshuidi.cloud.module.rooms.utils.NumberUtils;
import com.xiaoshuidi.cloud.module.system.api.apartment.ApartmentManageApi;
import com.xiaoshuidi.cloud.module.system.api.dept.DeptApi;
import com.xiaoshuidi.cloud.module.system.api.dept.dto.DeptLeaderRespDTO;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

import static com.xiaoshuidi.cloud.module.rooms.enums.ErrorCodeConstants.ADDRESS_ERROR;


/**
 * 门店 Service 实现类
 *
 * @author hans.zhang
 */

@Slf4j
@Service
@Validated
@RequiredArgsConstructor
public class ApartmentServiceImpl extends ServiceImpl<ApartmentMapper, Apartment> implements ApartmentService {

    private final ApartmentMapper apartmentMapper;
    private final ApartmentRepository apartmentRepository;
    private final CodeUtil codeUtil;
    private final RoomHouseRepository roomHouseRepository;
    private final RoomFloorRepository roomFloorRepository;
    private final RoomLayoutRepository roomLayoutRepository;
    private final RoomReservationRepository reservationRepository;
    private final DeptApi deptApi;
    private final RoomEsProducer roomEsProducer;
    private final BaiDuMapUtil baiDuMapUtil;
    private final BaiDuMapService baiDuMapService;
    private final ApartmentManageApi apartmentManageApi;
    private final ReserveApartmentConfigApi reserveApartmentConfigApi;


    @Override
    public List<ApartmentMapVO> getMap() {
        List<Apartment> apartments = apartmentMapper.selectList();
        List<ApartmentMapVO> apartmentMapVOS = new ArrayList<>();
        apartments.stream().forEach(apartment -> {
            ApartmentMapVO apartmentMapVo = new ApartmentMapVO();
            List<String> lnglat = new ArrayList<>();
            lnglat.add(apartment.getLongitude());// 经度
            lnglat.add(apartment.getLatitude()); // 维度
            //权重都设为1
            apartmentMapVo.setWeight(1);
            apartmentMapVo.setLnglat(lnglat);
            apartmentMapVo.setApartmentId(apartment.getId());
            apartmentMapVOS.add(apartmentMapVo);
        });
        return apartmentMapVOS;
    }

    @Override
    public List<ApartmentRespVO> getApartments(List<Long> apartmentIds) {
        // ids为空，则查询所有的门店
        if (ArrayUtil.isEmpty(apartmentIds)) {
            List<Apartment> apartments = apartmentMapper.selectList();
            return ApartmentConvert.INSTANCE.convertList(apartments);
        }
        // 查询id在apartmentIds中的门店
        List<Apartment> apartments = apartmentMapper.selectBatchIds(apartmentIds);
        return ApartmentConvert.INSTANCE.convertList(apartments);
    }

    /**
     * 批量更新经纬度
     */
    @Override
    public void updateLongitudeAndLatitude() {
        List<Apartment> apartments = apartmentMapper.selectList();
        apartments.stream().forEach(apartment -> {
            // 解析经纬度
            updateLocation(apartment);
            // 更新经纬度
            apartmentMapper.updateById(apartment);
        });
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<Boolean> delete(@NonNull Long apartmentId) {
        this.checkDelete(apartmentId);
        // 删除门店
        apartmentRepository.removeById(apartmentId);
        // 删除楼层
        roomFloorRepository.delByApartmentId(apartmentId);
        // 删除房间
        roomHouseRepository.delByApartmentId(apartmentId);
        // 删除户型
        roomLayoutRepository.delByApartmentId(apartmentId);
        return CommonResult.success(Boolean.TRUE);
    }

    /**
     * 分散式房源获取门店详情
     *
     * @param roomHouseId 房间id
     * @param loginUserId
     * @return
     */
    @Override
    public CommonResult<DistributedDetailRespVO> distributedDetail(@NonNull Long roomHouseId, Long loginUserId) {
        // 房间和门店校验
        RoomHouse roomHouse = roomHouseRepository.getById(roomHouseId);
        Assert.isTrue(ObjectUtil.isNotEmpty(roomHouse), "房源信息不存在");
        Apartment apartment = apartmentRepository.getById(roomHouse.getApartmentId());
        Assert.isTrue(ObjectUtil.isNotEmpty(apartment), "门店信息不存在");
        // 该房间下的所有子房间
        CommonResult<List<RoomHouse>> resp = roomHouseRepository.getBySuperId(roomHouseId);
        Assert.isTrue(resp.isSuccess(), "查询房间异常");
        List<RoomHouse> roomHouses = resp.getCheckedData();
        // 未停用的房间
        List<RoomHouse> inRentRoonHouse = roomHouses.stream().filter(p -> Boolean.FALSE.equals(p.getIsStop())).collect(Collectors.toList());
        // 房间信息
        Map<String, String> roomHouseInfo = new HashMap<>();
        for (int i = 1; i <= roomHouses.size(); i++) {
            roomHouseInfo.put("房间" + i, roomHouses.get(i - 1).getName());
        }
        // 房型信息
        RoomLayout roomLayout = new RoomLayout();
        if (ObjectUtil.isNotEmpty(roomHouse.getLayoutId())) {
            roomLayout = roomLayoutRepository.getById(roomHouse.getLayoutId());
            Assert.isTrue(ObjectUtil.isNotEmpty(roomLayout), "房型信息不存在");
        }

        // 构建响应对象
        DistributedDetailRespVO respVO = buildRespVO(roomHouse, apartment, roomLayout, roomHouses, inRentRoonHouse, roomHouseInfo);
        return CommonResult.success(respVO);
    }


    private DistributedDetailRespVO buildRespVO(RoomHouse roomHouse, Apartment apartment, RoomLayout roomLayout, List<RoomHouse> roomHouses, List<RoomHouse> inRentRoonHouse, Map<String, String> roomHouseInfo) {
        DistributedInfoVO distributedInfoVO = DistributedInfoVO.builder()
//                .apartmentName(apartment.getArea())
//                .address(apartment.getAddress())
//                .buildingNo(apartment.getBuildingNo())
//                .unitNo(apartment.getUnitNo())
                .floorNo(roomHouse.getFloorNo())
                .houseNo(roomHouse.getHouseNo())
                .province(apartment.getProvince())
                .city(apartment.getCity())
                .district(apartment.getDistrict())
//                .block(apartment.getBlock())
                .layoutName(roomLayout.getName())
                .space(roomHouse.getSpace())
                //.facetoType(roomLayout.getFaceToType())
                //.typeName(SourceTypeEnum.getNameByValue(apartment.getSourceType()))
                .build();

        DistributedRoomInfoVO distributedRoomInfoVO = DistributedRoomInfoVO.builder()
                .roomHouseNum(roomHouses.size())
                .roomHouseInfo(roomHouseInfo)
                .build();

        DistributedDetailRespVO respVO = DistributedDetailRespVO.builder()
                .address(apartment.getAddress())
//                .isWhole(apartment.getIsWhole())
                .roomHouseNum(roomHouses.size())
                .inRentNum(inRentRoonHouse.size())
                .distributedInfoVO(distributedInfoVO)
                .distributedRoomInfoVO(distributedRoomInfoVO)
                .remark(apartment.getRemark())
                .build();
        return respVO;
    }

    /**
     * 编辑门店信息
     *
     * @param editVO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<Boolean> edit(ApartmentEditVO editVO) {
        Apartment apartment = apartmentRepository.getById(editVO.getApartmentId());
        Assert.isTrue(ObjectUtil.isNotEmpty(apartment), "门店信息不存在");

        if (ObjectUtil.isNotEmpty(editVO.getPicUrl())) {
            String[] split = editVO.getPicUrl().split(",");
            Assert.isTrue(split.length <= 8, "照片数量不能超过8张");
        }
        if (ObjectUtil.isNotEmpty(editVO.getVideoUrl())) {
            String[] split = editVO.getVideoUrl().split(",");
            Assert.isTrue(split.length <= 1, "视屏数量不能超过1个");
        }
        if (ObjectUtil.isNotEmpty(editVO.getVrUrl())) {
            String[] split = editVO.getVrUrl().split(",");
            Assert.isTrue(split.length <= 1, "vr数量不能超过1个");
        }
        if (ObjectUtil.isNotEmpty(editVO.getTags())) {
            String[] tags = editVO.getTags().split(",");
            if (tags.length > 3) {
                throw new ServiceException(new ErrorCode(20044, "标签数量不能超过3个"));
            }
        }

        // 更新门店信息
        Apartment po = ApartmentConvert.INSTANCE.convert(editVO);
        po.setId(apartment.getId());
        po.setTenantId(apartment.getTenantId());
        po.setName(apartment.getName());
        po.setDeptId(apartment.getDeptId());
        // 更新经纬度
        // this.updateLocation(po);
        if (ObjectUtil.isAllNotEmpty(editVO.getLat(), editVO.getLng())) {
            po.setLatitude(editVO.getLat());
            po.setLongitude(editVO.getLng());
        }
        apartmentRepository.updateById(po);

        if(po.getIsConcentrated()){
            // 创建预约工单配置
            CreateReserveApartmentConfigReqVO reqVo = new CreateReserveApartmentConfigReqVO();
            reqVo.setApartmentId(po.getId());
            reqVo.setApartmentName(po.getName());
            reqVo.setDeptId(po.getDeptId());
            reserveApartmentConfigApi.createReserveApartmentConfig(reqVo);
        }

        // 同步更新后的经纬度到es
        List<RoomelUpdateReqVO> roomelUpdateReqVOS = new ArrayList<>();
        List<RoomHouse> roomHouses = roomHouseRepository.getByApartmentId(apartment.getId());
        roomHouses.forEach(roomHouse -> {
            // 更新ES数据
            RoomelUpdateReqVO roomelUpdateReqVO = new RoomelUpdateReqVO();
            roomelUpdateReqVO.setId(roomHouse.getId());
            roomelUpdateReqVO.setApartmentLat(po.getLatitude());
            roomelUpdateReqVO.setApartmentLon(po.getLongitude());
            roomelUpdateReqVOS.add(roomelUpdateReqVO);
        });
        log.info("--------门店信息修改，同步门店经纬度到es房源信息中--------");
        // 更新房源信息到es
        roomEsProducer.updateBatchRoomEl(roomelUpdateReqVOS);

        return CommonResult.success(Boolean.TRUE);
    }

    /**
     * 创建门店
     *
     * @param deptId        部门id
     * @param apartmentName 门店名
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<Long> create(@NonNull Long deptId, @NonNull String apartmentName, @NonNull Long tenantId) {
        // 创建一个只有名字的门店
        Apartment apartment = new Apartment();
        apartment.setId(deptId);
        apartment.setName(apartmentName);
        apartment.setNo(codeUtil.nextCode("GY"));
        apartment.setDeptId(deptId);
        apartment.setIsStop(false);
        apartmentRepository.save(apartment);
        //创建门店配置
        apartmentManageApi.creatApartment(deptId,apartmentName);
        //创建门店预定配置,默认未设置
        RoomReservationConfig reservationConfig = new RoomReservationConfig();
        reservationConfig.setApartmentId(apartment.getId());
        reservationConfig.setStatus(ReservationConfigStatusEnum.UN_SETUP.getCode());
        reservationConfig.setTenantId(tenantId);
        reservationRepository.save(reservationConfig);

        return CommonResult.success(apartment.getId());
    }

    /**
     * 查看门店详情
     *
     * @param apartmentId 门店id
     * @return
     */
    @Override
    public CommonResult<ApartmentVO> detail(Long apartmentId) {
        Apartment apartment = apartmentRepository.getById(apartmentId);
        Assert.isTrue(ObjectUtil.isNotEmpty(apartment), "门店信息不存在");
        ApartmentVO apartmentVO = ApartmentConvert.INSTANCE.convert(apartment);
        String ll = baiDuMapService.convertCoordinates(apartment.getLongitude() + "," + apartment.getLatitude(), 3, 5);
        if (StrUtil.isNotEmpty(ll)) {
            String[] split = ll.split(",");
            apartmentVO.setBaiduLat(split[0]);
            apartmentVO.setBaiduLong(split[1]);
        }
        return CommonResult.success(apartmentVO);
    }

    /**
     * 门店分页
     *
     * @param pageSize 每页大小
     * @param pageNum  第几页
     * @param name     门店名
     * @return
     */
    @Override
    public CommonResult<PageResult<ApartmentVO>> apartmentPageList(@NonNull Integer pageSize, @NonNull Integer pageNum, String name, Long apartmentId) {
        IPage<Apartment> page = apartmentRepository.page(new Page<Apartment>(pageNum, pageSize), name, apartmentId);
        List<ApartmentVO> apartmentVO = ApartmentConvert.INSTANCE.convert(page.getRecords());
        apartmentVO.stream().forEach(p -> {
            List<RoomHouse> roomHouses = roomHouseRepository.getByApartmentId(p.getId());
            p.setRoomHouseNum(roomHouses.size());
            CommonResult<DeptLeaderRespDTO> deptApiLeaderById = deptApi.getLeaderById(p.getDeptId());
            if (deptApiLeaderById.isSuccess()) {
                DeptLeaderRespDTO deptLeaderRespDTO = deptApiLeaderById.getCheckedData();
                p.setApartmentLeaderName(deptLeaderRespDTO.getNickName());
                p.setApartmentLeaderId(deptLeaderRespDTO.getLeaderUserId());
            }
        });
        PageResult<ApartmentVO> pageResult = new PageResult<>(apartmentVO, page.getTotal());
        return CommonResult.success(pageResult);
    }


    @Override
    public List<ApartmentListDto> listByIds(List<Long> ids) {
        List<Apartment> apartments = apartmentRepository.listByIds(ids);

        List<ApartmentListDto> list = ApartmentConvert.INSTANCE.convertToApartmentListDto(apartments);
        return list;
    }

    @Override
    public ApartmentListDto getById(Long id) {
        Apartment apartment = apartmentRepository.getById(id);
        ApartmentListDto dto = ApartmentConvert.INSTANCE.convertToApartmentListDto(apartment);
        return dto;
    }

    @Override
    public CommonResult<List<ApartmentVO>> myList(String apartmentName, Boolean isConcentrated) {
        LambdaQueryWrapper<Apartment> wrapper = Wrappers.lambdaQuery();
        wrapper.like(ObjectUtil.isNotEmpty(apartmentName), Apartment::getName, apartmentName);
        wrapper.eq(ObjectUtil.isNotEmpty(isConcentrated), Apartment::getIsConcentrated, isConcentrated);
        List<Apartment> apartments = this.list(wrapper);
        return CommonResult.success(ApartmentConvert.INSTANCE.convert(apartments));
    }

    /**
     * 校验门店是否可以删除
     *
     * @param apartmentId 门店id
     * @return
     */
    @Override
    public CommonResult<Boolean> checkDelete(@NonNull Long apartmentId) {
        Apartment apartment = apartmentRepository.myGetById(apartmentId);
        // 检查门店下是否有房型
        List<RoomLayout> roomLayouts = roomLayoutRepository.getByApartmentId(apartmentId);
        if (ObjectUtil.isNotEmpty(roomLayouts)) {
            throw new ServiceException(new ErrorCode(20033, "该门店下有房型信息，无法删除"));
        }
        // 检查门店下是否有房源
        List<RoomHouse> roomHouses = roomHouseRepository.getByApartmentId(apartmentId);
        if (ObjectUtil.isNotEmpty(roomHouses)) {
            throw new ServiceException(new ErrorCode(20034, "该门店下有房源数据，无法删除"));
        }
        return CommonResult.success(Boolean.TRUE);
    }

    @Override
    public CommonResult<Long> editApartmentName(@NonNull Long deptId, @NonNull String name) {
        log.info("修改门店名称feign接口被调用，deptId{}，name:{}", deptId, name);
        List<Apartment> apartments = apartmentRepository.getByDeptId(deptId);
        List<RoomelUpdateReqVO> roomelUpdateReqVOS = new ArrayList<>();
        for (Apartment apartment : apartments) {
            apartment.setName(name);
            updateById(apartment);
            // 同步修改es
            List<RoomHouse> roomHouses = roomHouseRepository.getByApartmentId(apartment.getId());
            // 更新ES数据
            roomHouses.forEach(roomHouse -> {
                RoomelUpdateReqVO roomelUpdateReqVO = new RoomelUpdateReqVO();
                roomelUpdateReqVO.setId(roomHouse.getId());
                roomelUpdateReqVO.setApartmentName(apartment.getName());
                roomelUpdateReqVOS.add(roomelUpdateReqVO);
            });
        }
        // 更新房源信息到es
        roomEsProducer.updateBatchRoomEl(roomelUpdateReqVOS);
        return CommonResult.success(deptId);
    }

    @Override
    @Transactional
    public CommonResult<Boolean> deleteByDeptId(Long deptId) {
        List<Apartment> apartments = apartmentRepository.getByDeptId(deptId);
        for (Apartment apartment : apartments) {
            this.checkDelete(apartment.getId());
            // 删除门店
            apartmentRepository.removeById(apartment.getId());
            // 删除楼层
            roomFloorRepository.delByApartmentId(apartment.getId());
            // 删除房间
            roomHouseRepository.delByApartmentId(apartment.getId());
            // 删除户型
            roomLayoutRepository.delByApartmentId(apartment.getId());
        }
        return CommonResult.success(Boolean.TRUE);
    }

    /**
     * 社区-获取推荐门店的信息
     *
     * @param apartmentIds
     * @param lat          用户维度
     * @param lon          用户经度
     * @return
     */
    @Override
    public CommonResult<List<RecommendApartmentInfoRespVO>> recommendApartmentInfo(List<Long> apartmentIds, String lat, String lon) {
        List<RecommendApartmentInfoRespVO> respVOS = new ArrayList<>();
        for (Long apartmentId : apartmentIds) {
            RecommendApartmentInfoRespVO respVO = new RecommendApartmentInfoRespVO();
            Apartment apartment = apartmentRepository.myGetById(apartmentId);
            // 门店下租金最低的房源
            List<RoomHouse> roomHouses = roomHouseRepository.getByApartmentIdOrderByMonthRental(apartmentId);
            if (ObjectUtil.isNotEmpty(roomHouses)) {
                RoomHouse roomHouse = roomHouses.get(0);
                respVO.setPrice(roomHouse.getMonthRental());
            }
            respVO.setStoreTel(apartment.getStoreTel());
            respVO.setApartmentName(apartment.getName());
            respVO.setApartmentId(apartmentId);
            respVO.setPicUrl(apartment.getPicUrl());
            respVO.setVideoUrl(apartment.getVideoUrl());
            respVO.setVrPicUrl(apartment.getVrPicUrl());
            respVO.setVrUrl(apartment.getVrUrl());
            respVO.setTags(apartment.getTags());

            StringBuilder sb = new StringBuilder();
            sb.append(StringUtils.isNotBlank(apartment.getProvince())?apartment.getProvince():"");
            sb.append(StringUtils.isNotBlank(apartment.getCity())?apartment.getCity():"");
            sb.append(StringUtils.isNotBlank(apartment.getDistrict())?apartment.getDistrict():"");
            sb.append(StringUtils.isNotBlank(apartment.getStreet())?apartment.getStreet():"");
            sb.append(StringUtils.isNotBlank(apartment.getAddress())?apartment.getAddress():"");
            respVO.setAddress(sb.toString());
            //门店下房型的数据
            List<RoomLayout> roomLayouts = roomLayoutRepository.getByApartmentId(apartmentId);
            List<RecommendApartmentInfoRespVO.LayoutInfo> layoutInfos = new ArrayList<>();
            roomLayouts.forEach(roomLayout -> {
                RecommendApartmentInfoRespVO.LayoutInfo layoutInfo = new RecommendApartmentInfoRespVO.LayoutInfo();
                layoutInfo.setLayoutId(roomLayout.getId());
                if (StrUtil.isNotEmpty(roomLayout.getPicUrl())) {
                    String[] split = roomLayout.getPicUrl().split(",");
                    layoutInfo.setPicUrl(split[0]);
                }
                layoutInfo.setName(roomLayout.getName());
                /*
                // 该房型下房源的最低价格
                List<RoomHouse> roomHousesByLayout = roomHouseRepository.getByApartmentIdAndLayoutIdOrderByMonthRental(apartmentId, roomLayout.getId());
                Double monthRentalByLayout = null;
                if (ObjectUtil.isNotEmpty(roomHousesByLayout)) {
                    monthRentalByLayout = roomHousesByLayout.get(0).getMonthRental();
                }
                layoutInfo.setPrice(monthRentalByLayout);*/
                layoutInfo.setPrice(NumberUtils.format(ObjectUtil.isNotEmpty(roomLayout.getMonthRental()) ? roomLayout.getMonthRental() : 0));
                // 当前房型下的空房数量
                layoutInfo.setEmptyRoomNum(roomHouseRepository.isHasEmptyRoom(roomLayout.getId()));
                // 当前房型下的房源数量
                layoutInfo.setRoomNum(roomHouseRepository.getRoomNumByRoomLayout(roomLayout.getId()));
                layoutInfos.add(layoutInfo);
            });
            respVO.setLayoutInfos(layoutInfos.stream().sorted(Comparator.comparing(RecommendApartmentInfoRespVO.LayoutInfo::getPrice, Comparator.nullsLast(String::compareTo))).collect(Collectors.toList()));

            if (StrUtil.isAllNotEmpty(lat, lon)) {
                String origins = lon + "," + lat;
                String destination = apartment.getLongitude() + "," + apartment.getLatitude();
                respVO.setMeter(baiDuMapUtil.walkingRoutePlanning(origins, destination, BaiDuMapUtil.WALKING, BaiDuMapUtil.DISTANCE));
            }

            respVOS.add(respVO);
        }
        log.info("获取推荐门店的信息响应数据:{}", JsonUtils.toJsonString(respVOS));
        return CommonResult.success(respVOS);
    }

    @Override
    public Apartment queryApartmentByName(String apartmentName) {
        LambdaQueryWrapper<Apartment> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Apartment::getName, apartmentName);
        return this.getOne(wrapper);
    }

    @Override
    public CommonResult<List<RecommendApartmentInfoRespVO>> recommendApartmentInfoByName(String apartmentName) {
        List<RecommendApartmentInfoRespVO> respVOS = new ArrayList<>();

        List<Apartment> apartments = apartmentRepository.getByName(apartmentName);
        for (Apartment apartment : apartments) {
            RecommendApartmentInfoRespVO respVO = new RecommendApartmentInfoRespVO();
            // 门店下租金最低的房源
            List<RoomHouse> roomHouses = roomHouseRepository.getByApartmentIdOrderByMonthRental(apartment.getId());
            if (ObjectUtil.isNotEmpty(roomHouses)) {
                RoomHouse roomHouse = roomHouses.get(0);
                respVO.setPrice(roomHouse.getMonthRental());
            }
            respVO.setStoreTel(apartment.getStoreTel());
            respVO.setApartmentName(apartment.getName());
            respVO.setApartmentId(apartment.getId());
            respVO.setPicUrl(apartment.getPicUrl());
            respVO.setVideoUrl(apartment.getVideoUrl());
            respVO.setVrPicUrl(apartment.getVrPicUrl());
            respVO.setVrUrl(apartment.getVrUrl());

            StringBuilder sb = new StringBuilder();
            sb.append(StringUtils.isNotBlank(apartment.getProvince())?apartment.getProvince():"");
            sb.append(StringUtils.isNotBlank(apartment.getCity())?apartment.getCity():"");
            sb.append(StringUtils.isNotBlank(apartment.getDistrict())?apartment.getDistrict():"");
            sb.append(StringUtils.isNotBlank(apartment.getStreet())?apartment.getStreet():"");
            sb.append(StringUtils.isNotBlank(apartment.getAddress())?apartment.getAddress():"");

            respVO.setAddress(sb.toString());
            respVOS.add(respVO);
        }
        return CommonResult.success(respVOS);
    }

    /**
     * 通过高德解析经纬度
     *
     * @param apartment
     */
    @Override
    public void updateLocation(Apartment apartment) {
        // 拼接路径
        String realAddress = apartment.getProvince() +
                apartment.getCity() +
                apartment.getDistrict() +
                apartment.getStreet() +
                apartment.getAddress() +
                (ObjectUtil.isNotEmpty(apartment.getName()) ? apartment.getName() : "");
        // 调用高德api查询经纬度
        String location = " , ";
        try {
            location = baiDuMapUtil.locationSearch(realAddress,apartment.getCity());
        } catch (Exception e) {
            log.info(e.getMessage());
            throw new ServiceException(ADDRESS_ERROR);
        }
        if (ObjectUtil.isEmpty(location)) {
            throw new ServiceException(ADDRESS_ERROR);
        }
        String[] split = location.split(",");
        apartment.setLongitude(split[0]);
        apartment.setLatitude(split[1]);
    }

    @Override
    public List<ApartmentGuessListResp> guessList() {
        List<Apartment> apartments = apartmentRepository.limit10List();
        if (CollectionUtil.isNotEmpty(apartments)) {
            List<ApartmentGuessListResp> resps = apartments.stream().map(s -> {
                ApartmentGuessListResp resp = new ApartmentGuessListResp();
                resp.setAptId(s.getId());
                resp.setAptName(s.getName());
                resp.setPicUrl(s.getPicUrl());
                return resp;
            }).collect(Collectors.toList());
            return resps;
        }
        return new ArrayList<>();
    }
}
